<template>
  <div id="main">
    <div class="trainConfig">
      <div style="font-size: 18px;font-weight: bold;color: rgb(70, 70, 70)">策略信息</div>
      <div style="margin-top: 20px;margin-bottom: 20px">
        <el-input v-model="stragyName" :disabled="true"></el-input>
      </div>
      <div style="font-size: 18px;font-weight: bold;color: rgb(70, 70, 70)">训练配置</div>
      <div v-if="showConfig" style="margin-top: 20px">
        <train-config :stragy-id="stragyId" />
      </div>
    </div>
    <div class="trainData">
      <div v-if="showTable">
        <line-charts :legend="legend" :series="series" :x-axis="xAxis" :title="title" />
      </div>
      <div v-else style="width: 700px; height: 450px;padding: 20px">
        <div class="background">
          <div style="position: relative;top: 190px;font-size: 30px;color: white;font-weight: bold">{{showTip}}</div>
        </div>
      </div>
      <div class="buttonGroup">
        <el-button type="primary" plain @click="startTrain">开始训练</el-button>
        <el-button type="danger" @click="stopTrain" plain>终止训练</el-button>
        <el-button type="warning" @click="exportData" plain>导出数据</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as XLSX from "xlsx";
import { blobValidate } from "@/utils/ruoyi";
import { globalHeaders } from "@/utils/request";
import axios from 'axios';
import { getStragyLsc, updateStragyStatus } from "@/api/lsc/strategy";
import FileSaver from 'file-saver';

const stragyId = ref("")
const stragyName = ref("")
const showTable = ref(false)
const showConfig = ref(false)
const legend = ref([] as any[])
const series = ref([] as any[])
const xAxis = ref([] as any[])
const title = ref('训练损失变化')
const showTip = ref('无训练数据')
const trainDataId = ref("")
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const baseURL = import.meta.env.VITE_APP_BASE_API;

onMounted(() => {
  stragyId.value = String(localStorage.getItem("stragyId"));
  stragyName.value = "策略名称：" + String(localStorage.getItem("stragyName"));
  showConfig.value = true;
})

const startTrain = async () => {
  showTip.value = "开始训练..."
  const response = await getStragyLsc(stragyId.value);
  trainDataId.value = String(response.data);
  console.log("ossId", response.data);
  await getData(String(response.data))
}
const stopTrain = () => {
  showTable.value = false
  showTip.value = "无训练数据"
}
const exportData = async () => {
  if (trainDataId.value == ""  || trainDataId.value == undefined) {
    proxy?.$modal.msgWarning("请先训练数据");
    return
  }
  const url = baseURL + '/resource/oss/download/' + trainDataId.value;
  const res = await axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: globalHeaders()
  });
  const blob = new Blob([res.data], { type: 'application/octet-stream' });
  console.log('blob', blob)
  FileSaver.saveAs(blob, decodeURIComponent(res.headers['download-filename'] as string));
}

const getData = async (ossId: string) => {
  const url = baseURL + '/resource/oss/download/' + ossId;
  const res = await axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: globalHeaders()
  });
  const isBlob = blobValidate(res.data);
  if (isBlob) {
    const blob = new Blob([res.data], { type: 'application/octet-stream' });
    console.log('blob', blob)
    await readExcel(blob)
    await updateStragyStatus(Object.assign({
      id: stragyId.value,
      trainStatus: 1,
    }))
  }
}

const readExcel = async (file: Blob) => {
  // 确保有文件可读
  if (!file) {
    alert('请先选择一个Excel文件');
    return;
  }
  series.value = [];
  const reader = new FileReader();
  // 读取文件完成后的回调
  reader.onload = (event) => {
    const data = new Uint8Array((event.target as any).result);
    // 使用 xlsx 读取数据
    const workbook = XLSX.read(data, { type: 'array' });
    console.log("data", workbook)
    // 获取第一个工作表
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = ref([] as any[])
    console.log("reader", jsonData.value)
    // 将 Excel 数据转换为 JSON 对象
    jsonData.value = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
    if (jsonData.value.length > 0) {
      jsonData.value[0].forEach((item: any) => {
        legend.value.push(item);
      });
    }
    xAxis.value = Array.from({ length: jsonData.value.length - 1 }, (_, i) => String(i + 1));
    for (let j = 0; j < jsonData.value[0].length; j++) {
      const colData = jsonData.value.slice(1).filter((row: string | any[]) => row.length >= 2).map((row: any[]) => row[j]);
      // 创建一个新的数据对象
      const newData = {
        name: legend.value[j],  // 使用 legend 中的数据作为 name 属性
        type: 'line',             // 设置 type 属性为 'line'
        smooth: true,
        data: colData             // 将列数据推导到 data 属性里
      };
      // 将数据对象添加到 dataDict 数组
      series.value.push(newData);
    }
    showTable.value = true;
    console.log("legend:", legend.value);
    console.log("series:", series.value);
  };
  // 读取文件为 ArrayBuffer
  reader.readAsArrayBuffer(file);
};
</script>

<style scoped lang="scss">
/* 样式 */

#main {
  background-color: #1ab394;
  padding: 10px;
  display: flex;
}
.trainData {
  padding: 20px;
  width: 750px;
  height: 520px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
  background-color: white;
  margin-left: 10px;
}
.trainData:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}
.buttonGroup {
  margin-left: 30px;
}
.trainConfig {
  width: 650px;
  height: 520px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
  background-color: white;
  padding: 20px;
  overflow: hidden;
}
.background {
  background-color: #707070;
  width: 100%;
  height: 100%;
  text-align: center;
}
</style>
